package cn.itcast.aspect;


import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.Collection;
import java.util.List;

//@Aspect
@Component
public class TrimStringAdvice {
    @Around("execution(* cn.itcast.controller.*Controller.*(..))")
    public Object trim(ProceedingJoinPoint pjp) throws Throwable {

        //1.获取前端拿到的参数
        Object[] args = pjp.getArgs();
        if (args != null) {
            //2.遍历数组,判断是否是String类型
            for (int i = 0; i < args.length; i++) {
                if (args[i] != null) {
                    //3.让每一个参数都去进行递归,在递归里去判断是不是字符串类型
                    args[i] = getParamIsString(args[i]);
                }

            }
        }

        Object result = pjp.proceed(args);
        return result;

    }

    private Object getParamIsString(Object arg) throws IllegalAccessException {
        if (arg == null) {
            return arg;
        }
        //获取arg的字节码对象
        Class<?> c = arg.getClass();
        //1.判断arg是否是字符串
        if (arg instanceof String) {
            //强转
            String str = ((String) arg).trim();
            return str;
        } else if (c.isArray()) {
            //是一个数组的话,我们就进行判断里面的元素
            //2.遍历数组
            Object[] arr = (Object[]) arg;
            for (int i = 0; i < arr.length; i++) {
                arr[i] = getParamIsString(arr[i]);
            }
            return arr;
        } else if (arg instanceof Collection) {
            //如果是集合
            Collection collection = (Collection) arg;
            if (collection instanceof List) {
                List list = (List) collection;
                for (int i = 0; i < list.size(); i++) {
                    Object o = list.get(i);
                    Object paramIsString = getParamIsString(o);
                    list.set(i, paramIsString);
                }
            } /*else {
                Set set = (Set) collection;
                Iterator iterator = set.iterator();
                while (iterator.hasNext()) {
                    Object o = iterator.next();
                    Object paramIsString = getParamIsString(o);
                    iterator.remove();
                    iterator.add(paramIsString);
                }
            }*/
            return collection;
        } else if (!c.getName().startsWith("java.") && !c.isPrimitive()) {
            //是一个自定义对象,通过反射获取属性,继续递归
            for (Field field : c.getDeclaredFields()) {
                field.setAccessible(true);
                Object o = field.get(arg);
                field.set(arg, getParamIsString(o));
            }
            return arg;
        } else {
            return arg;
        }

    }
}
